import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { hasToken } from '../../utils/storage';

export interface AuthRouteProps extends RouteProps {
  component: React.FC<any>;
  path: string;
}

export type LocationStateType = {
  from: string;
};

export default function AuthRoute(props: AuthRouteProps) {
  const { component: Comp, path, ...restProps } = props;
  return (
    <Route
      {...restProps}
      path={path}
      render={(_props) => {
        if (hasToken()) {
          return <Comp {..._props} />;
        }
        return (
          <Redirect
            to={{
              pathname: '/login',
              state: {
                from: path,
              } as LocationStateType,
            }}
          />
        );
      }}
    />
  );
}
